var tm = {};

tm.Main =
{
	init: function()
	{
		var stopListWords = ('STOP_LIST_WORDS'.translate()).split(' ');
		$(stopListWords).each(function (i, v) {
			var w = v.toLowerCase().replace([]);
			if (typeof stopListWords[v] == 'undefined') {
				stopListWords[v] = i;
			}
		});
		if (stopListWords && stopListWords instanceof Array && stopListWords.length > 0) {
			tm.Config.stopListWords = stopListWords;
		}
		else {
			tm.Config.stopListWords = [];
		}
		var frms = $('form:visible');
		if(frms.length > 0)
		{
			frms.each( function() { $(':input', this).focus( function() { this.hasFocus = true; } ).blur( function() { this.hasFocus = false; } ); } );
			//$(':input:visible:enabled', frms[0]).not($(':radio,:checkbox', frms[0])).get(0).focus();
		}
		Date.format = tm.Config.dateFormat;
	},
	getParam: function(name)
	{
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var tmpURL = window.location.href;
		var results = regex.exec( tmpURL );
		if( results === null ) {
			return "";
		} else {
			return results[1];
		}
	},
	pageName: function()
	{
		return window.location.href.replace(/^(.+[\/\\])([^\/\\\?]+)(\?.+)?$/, '$2');
	}
};

tm.String =
{
	translate: function(params)
	{
		if(tm.l18n && tm.l18n[this])
		{
			var str = tm.l18n[this], re;
			if(params)
			{
				for(param in params)
				{
					re = new RegExp('%' + param + '%', 'g');
					str = str.replace(re, params[param]);
				}
			}
			return str;
		}
		else
		{
			return this;
		}
	},
	escapeHTML: function()
	{
		return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g, '&quot;');
	  },
	unescapeHTML: function()
	{
		return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
	},
	countWords: function(simple)
	{
		if (typeof simple == 'undefined' || simple !== true) {
			simple = false;
		}
		var re1 = /[\.,:;\?\!\s\t\n\r]+/i;
		var re2 = /[-—_\s\t\n\r,\.:;\?\!"'`\(\)\[\]\{\}]+$/i;
		var words = this.split(re1);
		var wordsCounter = 0;
		$(words).each(function () {
			var word = this.replace(re2, '');
				if (simple && word.length > 0) {
					wordsCounter++;
				} else if (word.length > 2 && typeof tm.Config.stopListWords[word.toLowerCase()] == 'undefined') {
					wordsCounter++;
				}
		});
		return wordsCounter;
	},
	base64_encode: function()
	{
		var ks = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var s = '';
		var c1, c2, c3 = '';
		var e1, e2, e3, e4 = '';
		var i = 0;
		do
		{
			c1 = this.charCodeAt(i++);
			c2 = this.charCodeAt(i++);
			c3 = this.charCodeAt(i++);
			e1 = c1 >> 2;
			e2 = ((c1 & 3) << 4) | (c2 >> 4);
			e3 = ((c2 & 15) << 2) | (c3 >> 6);
			e4 = c3 & 63;
			if (isNaN(c2))
			{
				e3 = e4 = 64;
			}
			else if (isNaN(c3))
			{
				e4 = 64;
			}
			s = s + ks.charAt(e1) + ks.charAt(e2) + ks.charAt(e3) + ks.charAt(e4);
			c1 = c2 = c3 = e1 = e2 = e3 = e4 = "";
		}
		while (i < this.length);
		return s;
	},
	base64_decode: function()
	{
		var ks = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var s = "";
		var c1, c2, c3 = "";
		var e1, e2, e3, e4 = "";
		var i = 0;
		var re = /[^A-Za-z0-9\+\/\=]/g;
		if ( re.exec(this) )
		{
			return this;
		}
		var cs = this.replace(re, '');
		do
		{
			e1 = ks.indexOf(cs.charAt(i++));
			e2 = ks.indexOf(cs.charAt(i++));
			e3 = ks.indexOf(cs.charAt(i++));
			e4 = ks.indexOf(cs.charAt(i++));
			c1 = (e1 << 2) | (e2 >> 4);
			c2 = ((e2 & 15) << 4) | (e3 >> 2);
			c3 = ((e3 & 3) << 6) | e4;
			s = s + String.fromCharCode(c1);
			if (e3 != 64)
			{
				s = s + String.fromCharCode(c2);
			}
			if (e4 != 64)
			{
				s = s + String.fromCharCode(c3);
			}
			c1 = c2 = c3 = e1 = e2 = e3 = e4 = "";
		}
		while (i < cs.length);
		return s;
	}
};

String.prototype.translate = tm.String.translate;
String.prototype.escapeHTML = tm.String.escapeHTML;
String.prototype.unescapeHTML = tm.String.unescapeHTML;
String.prototype.countWords = tm.String.countWords;
String.prototype.base64_encode = tm.String.base64_encode;
String.prototype.base64_decode = tm.String.base64_decode;

$(tm.Main.init);

tm.b64 =
{
	init: function()
	{
		$('span.b64').each(function() {
			$(this).html($(this).html().base64_decode());
		});
		$('a[@class=b64]').each(function() {
			$(this).attr('href',$(this).attr('href').base64_decode());
		});
	}
};

$(tm.b64.init);

tm.ErrorMessage =
{
	alert: function(errors)
	{
		var message = 'ERR_FRM_HDR'.translate() + '\n\n';
		for(var i = 0; i < errors.length; i++)
		{
			message += '   - ' + errors[i] + ';' + '\n';
		}
		message += '\n' + 'ERR_FRM_FTR'.translate();
		alert(message);
	}
};

$(function () {
	var dateMin;
	if ($('input[@type="hidden"]#dateMin').length > 0)
	{
		var v = $('input[@type="hidden"]#dateMin').val();
		dateMin = Date.fromString(v);
	}
	tm.SearchForms.currentForm = $('#frm-hotel-search, #frm-car-search, #frm-package-search');
	$('.date-picker').each (
		function () {
			$(this).datepicker({
				showOn: 'button',
				duration: '',
				speed: '',
				numberOfMonths: 2,
				prevText: '&#x3c;&#x3c;',
				nextText: '&#x3e;&#x3e;',
				currentText: 'CURRENT_TEXT'.translate(),
				firstDay: 1,
				changeFirstDay: false,
				dayNamesMin: ['DOW_SHORT_SUN'.translate(),'DOW_SHORT_MON'.translate(),'DOW_SHORT_TUE'.translate(),'DOW_SHORT_WED'.translate(),'DOW_SHORT_THI'.translate(),'DOW_SHORT_FRI'.translate(),'DOW_SHORT_SAT'.translate()],
				monthNames: ['MONTH_LONG_JAN'.translate(), 'MONTH_LONG_FEB'.translate(), 'MONTH_LONG_MAR'.translate(), 'MONTH_LONG_APR'.translate(), 'MONTH_LONG_MAY'.translate(), 'MONTH_LONG_JUN'.translate(), 'MONTH_LONG_JUL'.translate(), 'MONTH_LONG_AUG'.translate(), 'MONTH_LONG_SEP'.translate(), 'MONTH_LONG_OCT'.translate(), 'MONTH_LONG_NOV'.translate(), 'MONTH_LONG_DEC'.translate()],
				//buttonImage: '../../i/icons/calendar.gif',
				buttonImage: '/i/calendar.gif',
				buttonImageOnly: true,
				buttonText: 'CALENDAR'.translate(),
				dateFormat: 'dd.mm.yy',
				displayClose: true,
				closeText: 'x',
				onClose: function() {
					if ($.browser.msie && $.browser.version.number < 7) {
						$('div.form_search_outer select').css('visibility', 'visible');
					}
				}
			});

			if (tm.SearchForms.currentForm.length > 0)
			{
				var currDatePicker = $('#' + this.id, tm.SearchForms.currentForm);
				if (currDatePicker.length > 0)
				{
					//currDatePicker.;
					var currDate = new Date();
					var min, sel = currDatePicker.val();
					min = dateMin;
					switch (this.id)
					{
						case 'depdate':
							if (sel == '')
							{
								sel = currDate.addDays(14).asString();
							}
						break;
						case 'enddate':
							var depDate = $('input#depdate').val();
							if (sel == '')
							{
								sel = currDate.addDays(21).asString();
								min = $(this).parents('form').attr('id') == 'frm-car-search' ? Date.fromString(sel) : Date.fromString(sel).addDays(1);
							}
							if (depDate != '')
							{
								min = $(this).parents('form').attr('id') == 'frm-car-search' ? Date.fromString(depDate) : Date.fromString(depDate).addDays(1);
							}
						break;
					}

					if ($('#frm-package-search').length > 0) {
						min = Date.fromString(currDatePicker.val());
						sel = min.addDays(14).asString();
						currDatePicker.datepicker('change', {
							'minDate': min
						});
					} else {
						currDatePicker.datepicker('change', {
							'onSelect': tm.SearchForms.dateSelected2,
							'minDate': min
						});
					}

					tm.SearchForms.dates[this.id] = sel;
					currDatePicker.val(sel);
				}
			}
		}
	);

	var
		rateChkd = false,
		rateInp = $('#hotel_search_outer .hotel-rating input'),
		rateInpLength = rateInp.size()
	;
	rateInp.change(function() {
		var $this = $(this);
		var sch = $this.parent(0).find('input:checked').size();
		if (sch == 0) {
			$this.attr('checked', 'checked');
			/*
			$this.siblings('input:checked').each(function() {
				sch++;
			});
			*/
		}
		/*
		if (sch == 0) {
			$this.attr('checked', 'checked');
		}
		*/
	});

	if ($.browser.msie && $.browser.version.number < 7) {
		$('.datepicker_trigger').click(function() {
			if ($('div.datepicker_multi').is(':visible')) {
				$(this).parents('div.form_search_outer').find('div.col-2 select, div.col-3 select').css('visibility', 'hidden');
			}
		});
	}

	$('input.date-picker').click(function() {
	   $(this).siblings('img.datepicker_trigger').triggerHandler('click');
	});
});

tm.Dates =
{
	getMonthesOptions: function(monthes, selectedMonth)
	{
		var res = '';
		for(i = 0; i < monthes.length; i++)
		{
			res += '<option value="' + (i+1) + '"' + ((selectedMonth > 0 && selectedMonth <= monthes.length && selectedMonth == i + 1) ? (' selected="selected"') : ('')) + '>' + monthes[i]+ '&nbsp;&nbsp;</option>';
		}
		return res;
	},
	getDaysOptions: function(selectedDay)
	{
		var res = '';
		for(i = 1, l = 31; i <= l; i++)
		{
			res += '<option value="' + i + '"' + ((selectedDay > 0 && selectedDay <= l && selectedDay == i) ? (' selected="selected"') : ('')) + '>' + ((i < 10) ? ('0') : ('')) + i + '&nbsp;&nbsp;</option>';
		}
		return res;
	},
	getYearsOptions: function(selectedYear)
	{
		var res = '';
		var curDate = new Date();
		for(i = curDate.getFullYear(), l = curDate.getFullYear() - 100; i >= l; i--)
		{
			res += '<option value="' + i + '"' + ((selectedYear > 0 && selectedYear <= curDate.getFullYear() && selectedYear == i) ? (' selected="selected"') : ('')) + '>' + i + '&nbsp;&nbsp;</option>';
		}
		return res;
	},
	/**
	 * Compares two dates
	 *
	 * Returns:
	 *   if date1 less then date2: -1
	 *   if date1 and date2 are same: 0
	 *   if date1 more than date2: 1
	 *
	 * NOTE: in comparision now used ONLY day, month and year!
	 */
	compare: function(date1, date2)
	{
		var d1, d2;
		if (typeof date1 == 'string') d1 = Date.fromString(date1)
		else d1 = date1;
		if (typeof date2 == 'string') d2 = Date.fromString(date2)
		else d2 = date2;

		d1 = d1.valueOf();
		d2 = d2.valueOf();

		if (d1 < d2) return -1;
		if (d1 == d2) return 0;
		return 1;
	}
};

tm.SearchForms =
{
	dates: {},
	currentForm: null,
	timer: null,
	init: function()
	{
		var frm = $('#frm-hotel-search, #frm-car-search');
		if (tm.SearchForms.currentForm === null && frm.length > 0)
		{
			tm.SearchForms.currentForm = frm;
		}
		if(!$.browser.msie || ($.browser.msie && $.browser.version.number > 5.5))
		{
			if(tm.SearchForms.currentForm && tm.SearchForms.currentForm.length > 0)
			{
				$('input[@type=text],input[@type=hidden],input[@type=checkbox],input[@type=radio],select', tm.SearchForms.currentForm.get(0)).each
				(
					function()
					{
						if(this.nodeName.toLowerCase() != 'input' || (this.type && (this.type.toLowerCase() != 'checkbox' && this.type.toLowerCase() != 'radio')))
						{
							if(this.nodeName.toLowerCase() == 'select')
							{
								$(this).bind
								(
									'change',
									tm.SearchForms.onFormChange
								);
							}
						}
						else
						{
							$(this).bind
							(
								'click',
								tm.SearchForms.onFormChange
							);
						}
					}
				);
				tm.SearchForms.currentForm.submit
				(
					function()
					{
						$('input[@type=hidden]:disabled', tm.SearchForms.currentForm).remove();
						return true;
					}
				);
			}
		}
	},
	onFormChange: function(e)
	{
		var elm = $(this);
		var elmId = elm.attr('id');

		$('.date-picker').blur();

	},

	dateSelected2: function(selectedDate, datePicker)
	{
		tm.SearchForms.dates[this.id] = selectedDate;
		if (this.id == 'depdate' && $("input#enddate").length > 0)
		{
			var enddate = $("input#enddate");
			var date = Date.fromString(selectedDate);

			$('div.form_search_outer').parents('form').attr('id') == 'frm-car-search' ? date : date.addDays(1);
			var cmpDates = tm.Dates.compare(date, tm.SearchForms.dates.enddate) > 0;
			if (enddate.val() == '' || cmpDates)
			{
				var strDate = date.asString();
				if (cmpDates)
				{
					tm.SearchForms.dates.enddate = strDate;
				}
				enddate.val(tm.SearchForms.dates.enddate);
			}

			//enddate.datepicker('change', {'minDate': Date.fromString(selectedDate).addDays(1)});
			enddate.datepicker('change', {'minDate': date});
		}
		else if (this.id == 'enddate')
		{
			var depdate = $("input#depdate");

			var cmpDates = tm.Dates.compare(tm.SearchForms.dates.depdate, selectedDate) > 0;
			if (cmpDates)
			{
				tm.SearchForms.dates.depdate = $('input[@type="hidden"]#dateMin').val();
			}
			if (depdate.val() == '')
			{
				$(this).datepicker('change', {'minDate': Date.fromString(tm.SearchForms.dates.depdate).addDays(1)});
				depdate.val(tm.SearchForms.dates.depdate);
			}
		}

		//$('div#cnt-top div.tabs ul.menu li.active a').focus();

		tm.SearchForms.currentForm.get(0).dataChanged = true;
		tm.SearchForms.onFormChange(this);
	}
};

$(tm.SearchForms.init);


/* Search form */
$(function() {
	var val, valId, valMore;
	$('.more-less-controls .more').click(function() {
		$(this).hide();
		$('.hotel_search_more').show();
		$('#adults-list').show();
		$('.more-less-controls .less').css('display', 'block');
	});
	$('.more-less-controls .less').click(function() {
		$(this).hide();
		$('.hotel_search_more').hide();
		$('#adults-list').hide();
		$('.more-less-controls .more').css('display', 'block');
	});
});

// Check for cookies enabled and browser
$(function() {
	if(!navigator.cookieEnabled) {
		$('#root').prepend('<div id="global-error">' + 'COOKIES_DISABLED'.translate() + '</div>');
	}
	if($.browser.msie && $.browser.version.number < 6) {
		$('#root').prepend('<div id="global-error">' + 'UPDATE_BROWSER'.translate() + '</div>');
	}
});